package com.itheima.service.store.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.itheima.annotation.Index;
import com.itheima.dao.store.QuestionDao;
import com.itheima.domain.store.Question;
import com.itheima.factory.MapperFactory;
import com.itheima.service.store.QuestionService;
import com.itheima.utils.TransactionUtil;
import org.apache.ibatis.session.SqlSession;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;


import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.lang.reflect.Field;
import java.util.*;

public class QuestionServiceImpl implements QuestionService {
    @Override
    public List<Question> findAll() {
        List<Question> all = null;
        SqlSession sqlSession = null;
        try {
            sqlSession = MapperFactory.getSqlSession();
            QuestionDao mapper = sqlSession.getMapper(QuestionDao.class);
            all = mapper.findAll();
            TransactionUtil.commit(sqlSession);
        } catch (Exception e) {
            TransactionUtil.rollback(sqlSession);
            e.printStackTrace();
        } finally {
            TransactionUtil.close(sqlSession);
        }
        return all;
    }

    @Override
    public Question findById(String id) {
        SqlSession sqlSession = null;
        Question question = null;
        try {
            sqlSession = MapperFactory.getSqlSession();
            QuestionDao mapper = sqlSession.getMapper(QuestionDao.class);
            question = mapper.findById(id);
            TransactionUtil.commit(sqlSession);
        } catch (Exception e) {
            TransactionUtil.rollback(sqlSession);
            e.printStackTrace();
        } finally {
            TransactionUtil.close(sqlSession);
        }

        return question;
    }

    @Override
    public void delete(String[] questionId) {
        SqlSession sqlSession = null;
        try {
            sqlSession = MapperFactory.getSqlSession();
            QuestionDao mapper = sqlSession.getMapper(QuestionDao.class);



            List itemList = mapper.findByQuestionId(questionId);
            if(itemList!=null){
                mapper.deleteItem(questionId);
            }
            mapper.delete(questionId);
            TransactionUtil.commit(sqlSession);
        } catch (Exception e) {
            TransactionUtil.rollback(sqlSession);
            e.printStackTrace();
        } finally {
            TransactionUtil.close(sqlSession);
        }
    }

    @Override
    public String save(Question question,Boolean flag) {
        SqlSession sqlSession = null;
        String picture =null;
        try {
            sqlSession = MapperFactory.getSqlSession();
            QuestionDao mapper = sqlSession.getMapper(QuestionDao.class);
           String id = UUID.randomUUID().toString();
            question.setId(id);
            if(flag){
                picture=id;
                question.setPicture(id+".jpg");

            }else{
                question.setPicture(picture);
            }

            //    private String reviewStatus;//审核状态  -1 审核不通过  0 审核中   1 审核通过
            question.setReviewStatus("0");
            question.setState("1");
            question.setCreateTime(new Date());
            mapper.save(question);
            TransactionUtil.commit(sqlSession);
        } catch (Exception e) {
            TransactionUtil.rollback(sqlSession);
            e.printStackTrace();
        } finally {
            TransactionUtil.close(sqlSession);
        }

        return picture;
    }

    @Override
    public void update(Question question,Boolean flag) {
        SqlSession sqlSession = null;
        try {
            sqlSession = MapperFactory.getSqlSession();
            QuestionDao mapper = sqlSession.getMapper(QuestionDao.class);
            if(flag){
                question.setPicture(question.getId()+".jpg");
            }else{
                question.setPicture(null);
            }
            mapper.update(question);
            TransactionUtil.commit(sqlSession);
        } catch (Exception e) {
            TransactionUtil.rollback(sqlSession);
            e.printStackTrace();
        } finally {
            TransactionUtil.close(sqlSession);
        }


    }

    @Override
    public PageInfo findAll(Integer pageNum, Integer pageSize) {
        PageInfo<Question> questionPageInfo = null;
        SqlSession sqlSession = null;
        try {
            sqlSession = MapperFactory.getSqlSession();
            QuestionDao mapper = sqlSession.getMapper(QuestionDao.class);
            PageHelper.startPage(pageNum, pageSize);
            List<Question> all = mapper.findAll();
            questionPageInfo = new PageInfo<>(all);
            TransactionUtil.commit(sqlSession);
        } catch (Exception e) {
            TransactionUtil.rollback(sqlSession);
            e.printStackTrace();
        } finally {
            TransactionUtil.close(sqlSession);
        }
        return questionPageInfo;
    }

    public ByteArrayOutputStream getReport()  {

        SqlSession sqlSession = null;
        Workbook wb = null;
        ByteArrayOutputStream baos = null;
        try {
            sqlSession = MapperFactory.getSqlSession();
            QuestionDao mapper = sqlSession.getMapper(QuestionDao.class);
            List<Question> questionList = mapper.findAll();
            FileInputStream is = new FileInputStream(new File("src/main/webapp/template/question_template.xlsx"));
            wb = new XSSFWorkbook(is);

            Sheet sheet = wb.getSheet("sheet1");

            CellStyle cs = wb.createCellStyle();
            cs.setAlignment(HorizontalAlignment.CENTER);
            cs.setVerticalAlignment(VerticalAlignment.CENTER);
            List<Map<Integer, String>> listData = new ArrayList<>();
            for (Question question : questionList) {
                listData.add(getFieldsData(question));
            }
            setDate(listData,sheet,cs);

            baos = new ByteArrayOutputStream();
            wb.write(baos);
            TransactionUtil.commit(sqlSession);
        } catch (Exception e) {
            TransactionUtil.rollback(sqlSession);
            e.printStackTrace();
        } finally {
            if(wb!=null){
                try {
                    wb.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            TransactionUtil.close(sqlSession);
        }
        return baos;
    }

    private void setDate(List<Map<Integer,String>> list,Sheet s,CellStyle cs) {
        int startRow=2;
        for (Map<Integer, String> map : list) {
            Set<Integer> keys = map.keySet();
            Row row = s.createRow(startRow);
            for (Integer index : keys) {
                String data = map.get(index);
                Cell cell = row.createCell(index);
                cell.setCellValue(data);
            }
            startRow++;
        }
    }

    /**
     * 反射获取对象的属性值与注解index的值作为键值对存入map
     * @param obj
     * @return
     * @throws IllegalAccessException
     */
    private Map<Integer,String> getFieldsData(Object obj) throws IllegalAccessException {
        Map<Integer,String> map = new HashMap<>();
        Class clazz = obj.getClass();
        Field[] fields = clazz.getDeclaredFields();
        for (Field field : fields) {
            field.setAccessible(true);
            Index annotation = field.getDeclaredAnnotation(Index.class);

            if (annotation != null) {
                int i = annotation.value();
                Object o = field.get(obj);
                if(o!=null){
                    map.put(i,o.toString());
                }else{
                    map.put(i,"");
                }
            }
        }
        return map;
    }




}
